from typing import List, Optional
from ..interfaces import PlatformAdapter, NormalizedContent
from ..vendor.mindspider.media_platform.tieba.client import TiebaClient


class TiebaAdapter(PlatformAdapter):
    def __init__(self, headers: Optional[dict] = None, proxy: Optional[str] = None):
        self.client = TiebaClient(headers=headers or {}, proxy=proxy)

    async def search_by_keywords(self, keywords: List[str], time_start: Optional[str], time_end: Optional[str]) -> List[NormalizedContent]:
        items: List[NormalizedContent] = []
        for kw in keywords:
            data = await self.client.search_by_keyword(kw, page=1)
            arr = data.get('items') or []
            for it in arr:
                nid = str(it.get('note_id') or '')
                title = it.get('title') or ''
                desc = it.get('description') or it.get('desc') or ''
                author = it.get('user_nickname') or ''
                url = it.get('note_url') or None
                items.append(NormalizedContent(platform='tieba', content_id=nid, author=author, title=title, text=desc, url=url, published_at=None, metrics={}, raw=it))
        return items

    async def fetch_by_accounts(self, accounts: List[str], time_start: Optional[str], time_end: Optional[str]) -> List[NormalizedContent]:
        items: List[NormalizedContent] = []
        for forum in accounts:
            data = await self.client.get_forum_threads(forum, page=1)
            arr = data.get('items') or []
            for it in arr:
                nid = str(it.get('note_id') or '')
                title = it.get('title') or ''
                desc = it.get('description') or it.get('desc') or ''
                author = it.get('user_nickname') or ''
                url = it.get('note_url') or None
                items.append(NormalizedContent(platform='tieba', content_id=nid, author=author, title=title, text=desc, url=url, published_at=None, metrics={}, raw=it))
        return items
